package zhr.chapter9;

import javax.swing.*;
import java.awt.*;
public class DocumentEventDemo extends JFrame {
    JTextArea inputText,showText;
    JMenuBar menubar;//菜单条
    JMenu menu;//菜单
    JMenuItem itemCopy,itemCut,itemPaste;//菜单选项 复制/剪切/粘贴
    TextListener textChangeListener;//input的监听器
    HandleListener handleListener;
    DocumentEventDemo() {
        init();
        setLayout(new FlowLayout());
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    void init(){
        inputText = new JTextArea(15,20);
        showText = new JTextArea(15,20);
        showText.setLineWrap(true);//文本自动换行
        showText.setLineWrap(true);//文本区以单词为界自动换行
        menubar = new JMenuBar();
        menu = new JMenu("编辑");
        itemCopy = new JMenuItem("复制(C)");
        itemCut = new JMenuItem("剪切(T)");
        itemPaste = new JMenuItem("粘贴(P)");
        itemCopy.setAccelerator(KeyStroke.getKeyStroke('c'));
        itemCut.setAccelerator(KeyStroke.getKeyStroke('t'));
        itemPaste.setAccelerator(KeyStroke.getKeyStroke('p'));
        itemCopy.setActionCommand("copy");
        itemCut.setActionCommand("cut");
        itemPaste.setActionCommand("paste");
        menu.add(itemCopy);
        menu.add(itemCut);
        menu.add(itemPaste);
        menubar.add(menu);
        setJMenuBar(menubar);
        add(new JScrollPane(inputText));//滚动窗格，实现内容增多时可水平/垂直滚动的效果
        add(new JScrollPane(showText));
        textChangeListener = new TextListener();
        handleListener =new HandleListener();
        textChangeListener.setInputText(inputText);
        textChangeListener.setShowText(showText);
        handleListener.setInputText(inputText);
        handleListener.setShowText(showText);
        (inputText.getDocument()).addDocumentListener(textChangeListener);
        //通过文档注册监听器
        itemCopy.addActionListener(handleListener);
        itemCut.addActionListener(handleListener);
        itemPaste.addActionListener(handleListener);
    }
}
